<template>
    <div>
        <div class="container">
            <div class="handle-box">
                <el-button type="primary" icon="el-icon-plus" @click="handleAdd">添加问题</el-button>
            </div>
            
            <el-table :data="tableData" border class="table" ref="multipleTable" element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)"
                v-loading="loading" header-cell-class-name="table-header">
                <el-table-column prop="id" label="序号" width="80" align="center"></el-table-column>
                <el-table-column prop="type" label="题目类型" width="120" align="center">
                    <template slot-scope="scope">
                        <span v-if="scope.row.type == '1'">单选</span>
                        <span v-else-if="scope.row.type == '2'">多选</span>
                        <span v-else-if="scope.row.type == '3'">输入框</span>
                        <span v-else-if="scope.row.type == '4'">生日</span>
                        <span v-else>{{ scope.row.type }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="title" label="问题标题" align="center"></el-table-column>

                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-edit"
                            @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button type="text" icon="el-icon-delete" class="red"
                            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination background layout="total, prev, pager, next" :current-page="query.pageIndex"
                    :page-size="query.pageSize" :total="pageTotal" @current-change="handlePageChange"></el-pagination>
            </div>
        </div>

        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="60%" :close-on-click-modal="false">
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="题目类型" prop="type" >
                    <el-select v-model="form.type" placeholder="请选择题目类型" :disabled="form.id" @change="handleTypeChange" clearable filterable
                        style="width: 100%">
                        <el-option label="单选" value="1"></el-option>
                        <el-option label="多选" value="2"></el-option>
                        <el-option label="输入框" value="3"></el-option>
                        <el-option label="生日" value="4"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="问题标题中文" prop="title">
                    <el-input v-model="form.title" placeholder="请输入问题标题"></el-input>
                </el-form-item>
                <el-form-item label="问题标题英文" prop="title">
                    <el-input v-model="form.e_title" placeholder="请输入问题标题"></el-input>
                </el-form-item>
                <template v-if="form.type === '1' || form.type === '2'">
                    <div v-for="(option, index) in form.options" :key="index" class="option-item">
                        <el-form-item label="选项中文" prop="options">
                            <el-row :gutter="24" align="middle">
                                <el-col :span="20">
                                    <el-input v-model="option.title" placeholder="请输入选项中文"
                                        ></el-input>
                                </el-col>
                            </el-row>
                        </el-form-item>
                        <el-form-item label="选项英文" prop="options">
                            <el-row :gutter="24" align="middle">
                                <el-col :span="20">
                                    <el-input v-model="option.e_title" placeholder="请输入选项英文"
                                        ></el-input>
                                </el-col>
                                <el-col :span="20">
                                    <el-button type="danger" icon="el-icon-delete" size="mini"
                                        @click="removeOption(index)" :disabled="form.options.length <= 1">
                                        删除
                                    </el-button>
                                    <el-button type="primary" icon="Refresh" size="mini"
                                        v-if="form.id"
                                        @click="handleBlur(index)">
                                        保存
                                    </el-button>
                                    <el-button type="primary" icon="el-icon-plus" @click="addOption"
                                        v-if="index === form.options.length - 1" class="add-option-btn">
                                        添加选项
                                    </el-button>
                                </el-col>
                            </el-row>
                        </el-form-item>
                    </div>
                </template>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleSubmit">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import AxiosPost from '../api/index'
export default {
    name: 'WjList',
    data() {
        return {
            loading: false,
            query: {
                search: '',
                pageIndex: 1,
                pageSize: 10
            },
            tableData: [],
            dialogVisible: false,
            isEdit: false,
            currentIndex: -1,
            pageTotal: 0,
            form: {
                id: '',
                type: null,
                title: '',
                options: [],
            },
            rules: {
                type: [
                    { required: true, message: '请选择题目类型', trigger: 'change' }
                ],
                title: [
                    { required: true, message: '请输入问题标题', trigger: 'blur' }
                ],
            }
        }
    },
    computed: {
        dialogTitle() {
            return this.isEdit ? '编辑问题' : '添加问题'
        }
    },
    mounted() {
        this.loadData()
    },
    methods: {
        async handleBlur(index) {
            if (this.form.options[index].id) {
                let option = {
                    is_wt: 2,
                    e_title: this.form.options[index].e_title,
                    id: this.form.options[index].id,
                    title: this.form.options[index].title,
                }
                let info = await AxiosPost('/admin/shop_wenda/updateWjdaan', option)
                if (info.code !== 10000) {
                    this.$message.error(info.message)
                    return false
                }
                this.$message.success(info.message)
            } else {
                let option = {
                    is_wt: 2,
                    add_id:this.form.id,
                    e_title: this.form.options[index].e_title,
                    title: this.form.options[index].title,
                }
                let info = await AxiosPost('/admin/shop_wenda/updateWjdaan', option)
                if (info.code !== 10000) {
                    this.$message.error(info.message)
                    return false
                }
                this.$message.success(info.message)
            }
            this.handleSearch()

        },
        handlePageChange(val) {
            this.$set(this.query, 'pageIndex', val);
            this.getData();
        },
        async loadData() {
            this.loading = true
            let info = await AxiosPost('/admin/shop_wenda/wjlist', this.query)
            if (info.code !== 10000) {
                this.$message.error(info.message)
                return false
            }
            this.loading = false
            this.tableData = info.data.list
            this.pageTotal = info.data.meta.total;
        },

        handleSearch() {
            this.$set(this.query, 'pageIndex', 1);
            this.loadData()
        },

        handleAdd() {
            this.isEdit = false
            this.resetForm()
            this.currentIndex = -1
            this.dialogVisible = true
            console.log(this.form);
            
        },

        handleEdit(index, row) {
            this.isEdit = true
            this.currentIndex = index
            // 深拷贝数据，确保选项数组正确复制
            this.form = JSON.parse(JSON.stringify(row))
            this.form.type = this.form.type + ''
            // 如果是单选或多选题但没有选项，初始化一个空选项
            this.dialogVisible = true
        },

        handleDelete(index, row) {
            this.$confirm('确认删除这个问题吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                let option = {
                    is_wt: 1,
                    id: row.id,
                }
                let info = await AxiosPost('/admin/shop_wenda/delWj', option)
                if (info.code !== 10000) {
                    this.$message.error(info.message)
                    return false
                }
                this.$message.success(info.message)
                this.handleSearch()
            }).catch(() => { })
        },

        handleTypeChange() {
            console.log('选择的题目类型:', this.form.type, typeof this.form.type)
            const selectedType = this.form.type
            // this.resetForm()
            this.form.type = selectedType
            // 如果选择单选或多选，初始化至少一个选项
            if (this.form.type === '1' || this.form.type === '2') {
                this.form.options = [{ title: '',e_title:'' }]
            }
        },

        addOption() {
            this.form.options.push({
                title: '',e_title:''
            })
            // 触发表单验证
            this.$nextTick(() => {
                this.$refs.form.validateField('options')
            })
        },

        async removeOption(index) {
            // 确保至少保留一个选项
            if (this.form.options.length <= 1) {
                this.$message.warning('至少需要保留一个选项')
            } else if(this.form.options[index].id) {
                let option = {
                    is_wt: 2,
                    id: this.form.options[index].id,
                }
                let info = await AxiosPost('/admin/shop_wenda/delWj', option)
                if (info.code !== 10000) {
                    this.$message.error(info.message)
                    return false
                }
                this.$message.success(info.message)
                this.form.options.splice(index, 1)
            }else{
                this.form.options.splice(index, 1)
            }
        },

        resetForm() {
            this.form = {
                type: null,
                title: '',
                e_title: '',
                options: [],
            }
        },

        async handleSubmit() {
            console.log(this.form);
            
            if(this.form.id){
                let option = {
                    id:this.form.id,
                    title:this.form.title,
                    e_title:this.form.e_title,
                    is_wt:1
                }
                let info = await AxiosPost('/admin/shop_wenda/updateWjdaan',option)
                if (info.code !== 10000) {
                    this.$message.error(info.message)
                    return false
                }
                this.$message.success(info.message)
                this.dialogVisible = false
            }else{
                console.log(this.form);
                
                let info = await AxiosPost('/admin/shop_wenda/saveWjdaan',this.form)
                if (info.code !== 10000) {
                    this.$message.error(info.message)
                    return false
                }
                this.$message.success(info.message)
                this.dialogVisible = false
            }
            this.handleSearch()
            

        }
    }
}
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-box .filter-item {
    margin-right: 10px;
}

.table {
    width: 100%;
    font-size: 14px;
}

.red {
    color: #ff0000;
}

.dialog-footer {
    text-align: right;
}

.option-item {
    margin-bottom: 10px;
}

.add-option-btn {
    margin-top: 10px;
}
</style>